//
//  SwapSelectIconController.swift
//  SCA
//
//  Created by tjun on 2025/9/10.
//

import UIKit


class SwapSelectCoinController: UIViewController {
    
    var fromRect: CGRect?
    var onSelectCoin: ((SwapCoinModel) -> Void)?

    private let datas: [SwapCoinModel]
    private var maskView: UIButton!
    private var contentView: UIView!
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.rowHeight = 44
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
        tableView.backgroundColor = .black
        tableView.contentInsetAdjustmentBehavior = .never;
        tableView.register(SwapCoinCell.self, forCellReuseIdentifier: SwapCoinCell.identifier)
        return tableView
    }()
    
    init(datas: [SwapCoinModel]) {
        self.datas = datas
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .custom
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
                
        view.backgroundColor = .clear
        
        maskView = UIButton(frame: view.bounds).addTo(view)
        maskView.backgroundColor = .black.withAlphaComponent(0)
        maskView.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        
        var contentW: CGFloat = 150
        datas.forEach { model in
           let textW = model.coinName.getSize(maxWidth: 300, font: UIFontMake(16)).width
           if textW + 60 > contentW {
               contentW = textW + 70
           }
        }
        
        contentView = UIView().addTo(view)
        contentView.backgroundColor = .black
        contentView.layer.borderColor = UIColorMake(0xC5C5C5).cgColor
        contentView.layer.borderWidth = 1
        contentView.layer.cornerRadius = 10
        contentView.layer.masksToBounds = true

        tableView.addTo(contentView)
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let totalH = min(self.datas.count, 5) * 44 + Int(tableView.contentInset.top + tableView.contentInset.bottom)
        
        if let fromRect = self.fromRect {
            
            var contentViewX = fromRect.maxX - contentW - 10
            if contentViewX < AppStyle.margin.left {
                contentViewX = AppStyle.margin.left
            }
            
            contentView.frame = CGRectMake(contentViewX, fromRect.maxY + 8, contentW, CGFloat(totalH))
        } else {
            contentView.frame = CGRectMake((view.width - contentW) * 0.5, (view.height - contentW) * 0.5 - 30, contentW, CGFloat(totalH))
        }
    }
    
    @objc func closeButtonTapped() {
        dismiss(completion: nil)
    }
    
    func dismiss(completion: (() -> Void)? = nil) {
        self.dismiss(animated: false, completion: completion)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.contentView.layer.transform = CATransform3DMakeScale(0.7, 0.7, 0.7)
        self.contentView.alpha = 0.7
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: .curveEaseIn) {
            self.contentView.alpha = 1
            self.contentView.layer.transform = CATransform3DMakeScale(1, 1, 1)
        }
    }
}


extension SwapSelectCoinController: UITableViewDataSource, UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SwapCoinCell.identifier, for: indexPath) as! SwapCoinCell
        let model = datas[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        datas.forEach { $0.isSelected = false }

        let model = datas[indexPath.row]
        model.isSelected.toggle()
        tableView.reloadData()
        
        onSelectCoin?(model)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            self.dismiss()
        })
    }
    
}
